package com.colldown.common;

import java.io.IOException;
import java.io.PrintWriter;
import java.lang.reflect.Method;
import java.math.BigDecimal;
import java.net.URLDecoder;
import java.sql.Timestamp;
import java.text.DecimalFormat;
import java.util.Date;
import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
/**
 * 常用的工具类
 */
public class A_Tools {
	
	public static String  strUserArea="";//GLXY 管理学院专属标示 
	/**
	 * 根据参数名从request中取得值并转换为UTF-8格式
	 * @param request
	 * @param name
	 * @return String 值
	 */
	public static String getParameter(HttpServletRequest request, String name,String format) {
		return decode(request.getParameter(name),format);
	}

	
	/**
	 * 查询列表自定义sql查询 list转为与po对应的json并输出
	 * @param list  sql语句(字段别名中可能含"_",所以字段名需与po中的属性一致)查询出的结果 List<Map<String, Object>>
	 * @param count 查询列表总条数
	 * @param po    po类
	 * 
	 */
	@SuppressWarnings("unused")
	public static void listToJson(HttpServletResponse response, List list,int count){
		try{
			Gson gson = new GsonBuilder().create();
			String json = gson.toJson(list);
			String result = "{total:" + count + ",data:" + json + "}";//
			printJson(response, result);
		}catch(Exception e){
			printJson(response, "[]");
		}
		
	}
	
	public static String listToJson(List list){
		try{
			Gson gson = new GsonBuilder().create();
			String json = gson.toJson(list);
			return json;
		}catch(Exception e){
			return "[]";
		}
		
	}
	/*
	public static void listToJson2(HttpServletResponse resp, List<Map<String, Object>> list,int count,Object po) {
		 String result="";
		 if (list != null && list.size() > 0) {
	     List<Map<String, Object>> listCopy=new ArrayList<Map<String,Object>>();
		 Field[] fs=po.getClass().getDeclaredFields();//字段 数组
		 Set<String> set= list.get(0).keySet();//sql字段名 （可能含“_”）
//		 Map<String,String> keyPoMap=new HashMap<String, String>();//sql字段与替换“_”后的集合
//		 Iterator<String> it=set.iterator();
//		 while(it.hasNext()){
//			 String sqlKey=it.next();
//			 keyPoMap.put(sqlKey.replaceAll("_", ""), sqlKey);
//		 }
//		 Set<String> keySet=keyPoMap.keySet();//替换“_”后的key集合
		 
		 for (int m = 0; m < list.size(); m++) {//替换map的key
			  Map<String, Object> map=list.get(m);
			  Map<String, Object> mapCopy=new HashMap<String, Object>();
				if(fs != null){
				for(int i=0; i<fs.length; i++){
					String fname = fs[i].getName();
					String fnameToUp=fname.toUpperCase();
					if(set.contains(fnameToUp)){
						mapCopy.put(fname, map.get(fnameToUp));
					}
				}
				listCopy.add(mapCopy);
			}
		}
		 
		 if(listCopy!=null&&listCopy.size()>0){
			 Gson gson = new GsonBuilder().setDateFormat("yyyy-MM-dd HH:mm:ss").create();
			 result = gson.toJson(listCopy);
		 }
			if (result.length() > 0) {
				result = "{total:" + count + ",data:" + result + "}";//
			} else {
				result = "[]";
			}
			printJson(resp,result);
		 }
		 else{
			printJson(resp, "[]");
		 }
	}
	*/

	/**
	 * 解码功能
	 * 功能: 这个方法处理ajax提交中文时的乱码问题，使用这个方法时，字符串在提交之前，先要用encodeURI 处理一下。
	 * @param code
	 * @param format 
	 * @return String
	 */
	public static String decode(String code,String format) {
		if ("".equals(NullToStr(code))){
			return "";
		}
		try {
			return URLDecoder.decode(code,format);
		} catch (Exception e) {
			code = "";
		}
		return code;
	}

	/**
	 * 如果为空对象则返回空字符，否则返回原字符串
	 * @param Object
	 * @return String
	 */
	public static String ToString(Object o) {
		String str = null;
		if (o == null) {
			str = "";
		} else {
			str = o.toString();
		}
		return str;
	}

	/**
	 * 将字对象强转字符串 null时返回空
	 */
	   public static  String NullToStr(Object obj) {
           if (obj != null && !"null".equals(obj)) {
               return obj.toString().trim();
           } else {
               return "";
           }
       }
	/**
	 * 将对象强转成 Double数字型 不是数字时返回0
	 */
    public static  Double NullToDouble(Object obj){
        if (obj != null){
            try{
                return   Double.valueOf(obj.toString().trim());
            }
            catch(Exception e){
                return 0D;
            }
        }
        else{
            return 0D;
        }
    }
    /**
	  * 将对象强转成 int 数字型 不是数字时返回0
	  */
    public static  Integer NullToNumber(Object obj){
        if (obj != null){
            try{
                return   Integer.parseInt(obj.toString().trim());
            }
            catch(Exception e){
                return 0;
            }
        }
        else{
            return 0;
        }
    }
	/**
	  * 将对象强转成结尾为0.00的String 
	 */
    public static  String NullToDecimalFormat(Object obj,String strParse){
 	   if("".equals(NullToStr(strParse)) ){
 		   strParse=".";
 	   }
 	   DecimalFormat df2=new DecimalFormat(strParse); 
       if (obj != null){
            try{
                return   df2.format(NullToDouble(obj));
            }
            catch(Exception e){
                return strParse;
            }
        }
        else{
            return strParse;
        }
    }
	/**
	 * 格式化字符串
	 * @param str
	 * @return
	 */
	public static String farmatStr(String str){
		//消费类型ID
		StringBuffer strBuff=new StringBuffer();
		String[] strs=str.split(",");
		String resultStr="";
		if(strs!=null&&strs.length>0){
			for(int i=0;i<strs.length;i++){
				strBuff.append("'"+strs[i]+"',");
			}
		}
		if(strBuff.length()>0){
			strBuff.deleteCharAt(strBuff.length()-1);
			resultStr=strBuff.toString();
		}
		return resultStr;	
	}
	/**
	 * 将符合要求的值分成固定数量以便查询
	 * @param strIds 符合要求的值
	 * @param strFiled	该字段在数据库中对应的字段名
	 * @return
	 */
	public static String getSqlIn(String strIds,String strFiled){
		String sWhere="";
		int t=900; //每组的个数，最大为1000
		String [] date=strIds.split(",");
		if(date.length>t){
			sWhere+=" "+strFiled+" in ("+StrDH( strIds.substring(0,strIds.indexOf(date[t])-1))+") or "+getSqlIn(strIds.substring(strIds.indexOf(date[t])), strFiled);
		}else{
			sWhere+=" "+strFiled+" in ("+StrDH(strIds)+") ";
		}
		
		return sWhere;
	}
    /**
	 * 取得字符串 规范后 符合逗号分隔的规则串,用来Splite分割成数组用
	 */
    public  static  String StrDH(String vTmp)
    {
        String strTmp = "";
        if (vTmp == null||"".equals(vTmp)) { return "''"; }
        String schar = "\uff0c";
        vTmp = vTmp.trim();
        vTmp = vTmp.replace(schar, ",");
        String[] str = vTmp.split(",");
        for (int i = 0; i < str.length; i++){
            if (str[i].trim() != ""){
                strTmp = ("".equals(strTmp) ? strTmp : strTmp + ",") +"'"+ str[i]+"'";
            }
        }
        return strTmp;
    }
    /**
     * 去掉,分隔值的重复数据
     * @param vValue
     * @return
     */
    public static  String GetDistinctValue(String vValue)
    {
        if (vValue == null || vValue == "") { return ""; }
        vValue = StrDH(vValue);
        boolean IsSame = false;
        String[] sV = vValue.split(",");
        for (int i = 0; i < sV.length; i++){
            IsSame = false;
            for (int j = 0; j < sV.length; j++){
                if (sV[i] == sV[j] && IsSame){
                    sV[i] = "";
                }
                if (sV[i] == sV[j]){
                    IsSame = true;
                }
            }
        }
        vValue = "";
        for (int i = 0; i < sV.length; i++){
            vValue = vValue + "," + sV[i];
        }
        vValue =  StrDH(vValue);
        return vValue;
    }
	/**
	 * 格式化传入SQL like关键字中的搜索文字，替换掉关键字
	 * 
	 * @param Object
	 * @return String
	 */
	public static String formatLikeString(String searchText) {
		if (isBlank(searchText)) {
			searchText = "";
		}
		searchText = searchText.replace("/", "//").
		replace("'", "''").replace(
				"%", "/%").replace("％","/％").replace("_", "/_").replace("[", "/[").replace("]",
				"/]").replace("^", "/^");
		return searchText;
	}
	

	/**
	 * 将无格式的文本处理成有格式的文本
	 * @param str  要处理的文本
	 * @return 返回带换行等格式的文本
	 */
	public static String replaceString(String str) {
		if (isBlank(str) == true) {
			return ("&nbsp;");
		} else {
			str = str.replace("\r\n", "<br />").replace("\r", "<br />").replace("\n", "<br />").replace("\t", "　　");
			return (str);
		}
	}

	/**
	 * 把传过来的字符串里面的特殊字符替换成新的字符；
	 * @param oldString
	 * @return
	 */

	public static String StringCode(String StringCode){
		if (StringCode == null)
			return "";
		try {
			return new String(StringCode.getBytes("UTF-8"),"GBK");
		} catch (Exception e) {
			StringCode = "";
		}
		return StringCode;
	}
	
	
  	private static String[] values = {"0","一","二","三","四","五","六","七","八","九"};
	private static String FLOOR = "层";
	private static String SHI = "十";
	/**
	 * 根据传过来数值转化成大写数字
	 * @param value
	 * @return
	 */
	public static String getDS(int value){
		StringBuffer data = new StringBuffer();
		if(value<10){
			data.append(values[value]);
			data.append(FLOOR);
		}
		if(value==10){
			data.append(SHI);
			data.append(FLOOR);
		}
		if(value>10 && value<100){
			//解析所传过来每一位数字
			String tmp = String.valueOf(value);
			if(value>=20){
				data.append(values[new Integer(String.valueOf(tmp.charAt(0))).intValue()]);
				data.append(SHI);
				if(new Integer(String.valueOf(tmp.charAt(1))).intValue()!=0){
					data.append(values[new Integer(String.valueOf(tmp.charAt(1))).intValue()]);
				}
				data.append(FLOOR);
			}else{
				data.append(SHI);
				data.append(values[new Integer(String.valueOf(tmp.charAt(1))).intValue()]);
				data.append(FLOOR);
			}
		}
		return data.toString();
	};
	/**
	 * 
	 * @param target 目标字符串
	 * @param split  分格符
	 * @return '',''这样的格式
	 */
	public static String getWeaveOracle(String target,String split){
		String [] temp = target.split(split);
		StringBuffer value = new StringBuffer();
		if(target!=null && target.length()>0){
			for(int i=0;i<temp.length;i++){
				if(i!=temp.length-1){
					value.append("'").append(temp[i]).append("',");
				}else{
					value.append("'").append(temp[i]).append("'");
				}
			}
			return value.toString();
		}
		return "''";
	}
	/**
	 * 对象的copy
	 * @param vo 目标
	 * @param po 拷贝值
	 * @return
	 * @throws Exception
	 */
	@SuppressWarnings("unchecked")
	public static Object copy(Object vo,Object po) throws Exception{
		//获取vo对象的Method数组
		Method []vo_methods = vo.getClass().getDeclaredMethods();
		//po的Method对象
		Method method_po = null;
		for(int i=0;i<vo_methods.length;i++){
			//获取vo对象的Method
			Method vo_method = vo_methods[i];
			//获取vo的方法名称
			String vo_methodName = vo_method.getName();
			//获取方法的前三个字母(就是get或着set)
			String three_var = vo_methodName.substring(0, 3);
			if("get".equals(three_var)){
				//获取po对象的方法
				String po_method_name = getPoMethod(vo_methodName,po);
				if(po_method_name==null){
					continue;
				}
				Method method = vo.getClass().getMethod(vo_methodName);
				//get方法所返回的类型
				Class inner_class = method.getReturnType();
				//相应类型的转换方式
				if("java.lang.String".equals(inner_class.getName())){
					String returnValue = (String)method.invoke(vo);
					method_po = po.getClass().getMethod(po_method_name,new Class[]{String.class});
					method_po.invoke(po,returnValue);
				}
				if("int".equals(inner_class.getName())){
					int returnValue = (Integer)method.invoke(vo);
					method_po = po.getClass().getMethod(po_method_name,new Class[]{int.class});
					method_po.invoke(po,returnValue);
				}
				if("java.util.Date".equals(inner_class.getName())){
					Date returnValue = (Date)method.invoke(vo);
					method_po = po.getClass().getMethod(po_method_name,new Class[]{Date.class});
					method_po.invoke(po,returnValue);
				}
				if("java.math.BigDecimal".equals(inner_class.getName())){
					BigDecimal returnValue = (BigDecimal)method.invoke(vo);
					method_po = po.getClass().getMethod(po_method_name,new Class[]{BigDecimal.class});
					method_po.invoke(po,returnValue);
				}
				if("java.sql.Timestamp".equals(inner_class.getName())){
					Timestamp returnValue = (Timestamp)method.invoke(vo);
					method_po = po.getClass().getMethod(po_method_name,new Class[]{Timestamp.class});
					method_po.invoke(po,returnValue);
				}
			}
		}
		return vo;
	}
	//直接返回Method对象
	private static String getPoMethod(String method_name,Object po) {
		String methodName = "set"+method_name.substring(3, method_name.length());
		Method []methods = po.getClass().getDeclaredMethods();
		boolean flag = false;
		for(int i=0;i<methods.length;i++){
			//如果po里有这样的方法则返回
			if(methods[i].getName().equals(methodName)){
				flag = true;
				break;
			}
		}
		//如果flag为true说明po中存在相应的方法
		if(flag){
			return methodName;
		}
		return null;
	}
	/**
	 * 数字金额大写转换，思想先写个完整的然后将如零拾替换成零
	 * 要用到正则表达式
	 */
	public static String digitUppercase(double n){
		String fraction[] = {"角", "分"};
	    String digit[] = { "零", "壹", "贰", "叁", "肆", "伍", "陆", "柒", "捌", "玖" };
	    String unit[][] = {{"元", "万", "亿"},
	                 {"", "拾", "佰", "仟"}};

	    String head = n < 0? "负": "";
	    n = Math.abs(n);
	    
	    String s = "";
	    for (int i = 0; i < fraction.length; i++) {
	        s += (digit[(int)(Math.floor(n * 10 * Math.pow(10, i)) % 10)] + fraction[i]).replaceAll("(零.)+", "");
	    }
	    if(s.length()<1){
		    s = "整";	
	    }
	    int integerPart = (int)Math.floor(n);

	    for (int i = 0; i < unit[0].length && integerPart > 0; i++) {
	        String p ="";
	        for (int j = 0; j < unit[1].length && n > 0; j++) {
	            p = digit[integerPart%10]+unit[1][j] + p;
	            integerPart = integerPart/10;
	        }
	        s = p.replaceAll("(零.)*零$", "").replaceAll("^$", "零") + unit[0][i] + s;
	    }
	    return head + s.replaceAll("(零.)*零元", "元").replaceFirst("(零.)+", "").replaceAll("(零.)+", "零").replaceAll("^整$", "零元整");
	}
	

	/**
	 * 解析项目负责人名称
	 * @param allDirector
	 * @param type
	 * @return
	 */
	public static String getDirector(String allDirector,String type){
		String[] directorName=allDirector.split(",");
		String director="";
		String[] temp=new String[2];
		for(int i=0 ;i<directorName.length;i++){
			temp=directorName[i].split("#");
			if(temp.length>0&&temp[0].equals(type)){
				director+=","+temp[1];
			}
		}
		if(!isBlank(director)&&director.length()>0){
			director=director.substring(1);
		}
		return director;
	}
	/**
	 * 截取字符串，后边加"..."
	 * src：源字符串，len:要截取的长度，fix:要添加的后缀
	 * @return
	 */
	public static String getShortStrFromLong(String src,int len,String fix){
		String returnStr="";
		if(NullToStr(src).length()>len){
			returnStr=src.substring(0,len)+fix;
			
		}else{
			returnStr=src;
		}
		return returnStr;
		
	}
    /**
     * 验证字符串不为空
     * @param obj
     * @return
     * zj 2014-2-17
     */
    public static boolean vaildateStrNull(String obj){
   	 if(obj != null && !obj.equals("null") && !obj.equals("")){
 			return true;
 		 }
   	 return false;
     }
    /**
     * 验证是否为空  为空返回true
     * @param str
     * @return
     */
	
	public static boolean isBlank(String str){
		boolean bool = false;
		if(str==null || "".equals(str) || "".equals(str.trim())){
			bool = true;
		}
		return bool;
	}
	
	
	/**
	 * @param String resultJson {'key1':'value1','key2':'value2'}
	 * @return void
	 */
	public static  void printJson(HttpServletResponse response,String resultJson){
		
		response.setContentType("charset=UTF-8");
		response.setHeader("pragma", "no-cache");
		response.setHeader("cache-control", "no-cache");
		PrintWriter out=null;
		try{
		 out = response.getWriter();
		 out.print(resultJson);
		 out.flush();
		}catch(IOException e){
			
		}finally{
			out.close();
		}
		
	}
	
	
}

